package com.lins.store.controller;

import com.lins.store.entity.ex.*;
import com.lins.common.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

@Slf4j
public class BaseController {
    public static final int OK = 200;

    /** 用于统一处理方法抛出的异常，不止要 UserException 也要 FileUploadException */
    @ExceptionHandler({UserException.class, FileUploadException.class})
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof NullPointerException){
            result.setState(1000);
        } else if (e instanceof UsernameDuplicateException) {
            result.setState(4000);
        } else if (e instanceof UserNotFoundException) {
            result.setState(4001);
        } else if (e instanceof PasswordNotMatchException) {
            result.setState(4002);
        } else if (e instanceof AccessDeniedException) {
            result.setState(4005);
        } else if (e instanceof InsertException) {
            result.setState(5000);
        } else if (e instanceof UpdateException) {
            result.setState(5001);
        } else if (e instanceof DeleteException) {
            result.setState(5002);
        } else if (e instanceof FileEmptyException) {
            result.setState(6000);
        } else if (e instanceof FileSizeException) {
            result.setState(6001);
        } else if (e instanceof FileTypeException) {
            result.setState(6002);
        } else if (e instanceof FileStateException) {
            result.setState(6003);
        } else if (e instanceof FileUploadIOException) {
            result.setState(6004);
        }
        return result;
    }

    protected final String getUidFromSession(HttpSession session){
        /**
         * 我发现平常其实走到不这一步，因为假如session不存在了(被注销)，请求过来时会被框架(dispatcherServlet)拦截，接口返回Exception
         * 假如session失效或被删除，这里才会人为拦截并记录日志，防止被动的抛出异常。
         */
        if(session == null){
            log.error("session是空的!!!");
            return null;
        }
        Object uid = session.getAttribute("uid");
        if (uid == null) throw new UserNotFoundException("从session中未取出uid");
        return uid.toString();
    }

    protected final String getUsernameFromSession(HttpSession session){
        if(session == null){
            log.error("session是空的!!!");
            return null;
        }
        Object username = session.getAttribute("username");
        if (username == null) throw new UserNotFoundException("从当前会话中未取出用户名");
        return username.toString();
    }



}
